package com.itheima.web;

import com.itheima.pojo.*;
import com.itheima.service.BrowseGoodsRecordService;
import com.itheima.service.ItemService;
import com.itheima.service.PurchaseHistoryService;
import com.itheima.service.ShoppingCartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@WebServlet("/recommendationServlet")
public class RecommendationServlet extends HttpServlet {
    private BrowseGoodsRecordService browseGoodsRecordService = new BrowseGoodsRecordService();
    private PurchaseHistoryService purchaseHistoryService = new PurchaseHistoryService();
    private ShoppingCartService shoppingCartService = new ShoppingCartService();
    private ItemService itemService = new ItemService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        算法思路：
        1. 对每个用户分别查询BrowseGoodsRecord、PurchaseHistory和ShoppingCart表,获得其itemName
        2. 对于每个商品,如果这个商品的itemName在BrowseGoodsRecord、PurchaseHistory和ShoppingCart中,它的推荐度就+1
        */

        // 通过session获取user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();

        List<BrowseGoodsRecord> browseGoodsRecords = browseGoodsRecordService.selectByUserId(userId);
        List<PurchaseHistory> purchaseHistories = purchaseHistoryService.selectByBuyerId(userId);
        List<ShoppingCart> shoppingCartGoods = shoppingCartService.selectByBuyerId(userId);
        List<Item> items = itemService.selectAll();

        // 用于记录每个itemId的推荐度
        HashMap<Integer, Integer> recommendationDict = new HashMap<>();
        // 初始化recommendationDict,设置推荐度为0
        for (Item item : items) {
            recommendationDict.put(item.getId(), 0);
        }

        for (Item item : items) {
            for (BrowseGoodsRecord browseGoodsRecord : browseGoodsRecords) {
                if (browseGoodsRecord.getItemName().equals(item.getItemName())) {
                    Integer value = recommendationDict.get(item.getId()) + 1;
                    recommendationDict.put(item.getId(), value);
                }
            }

            for (PurchaseHistory purchaseHistory : purchaseHistories) {
                if (purchaseHistory.getItemId().equals(item.getId())) {
                    Integer value = recommendationDict.get(item.getId()) + 1;
                    recommendationDict.put(item.getId(), value);
                }
            }

            for (ShoppingCart shoppingCartGood : shoppingCartGoods) {
                if (shoppingCartGood.getItemId().equals(item.getId())) {
                    Integer value = recommendationDict.get(item.getId()) + 1;
                    recommendationDict.put(item.getId(), value);
                }
            }
        }

        // 创建一个List对象，用于存储HashMap中的所有键值对
        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(recommendationDict.entrySet());

        // 使用Collections.sort()方法对List对象进行排序，排序的依据是HashMap的value值，从大到小排序
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        // 创建一个新的List对象，用于存储value最大的三个键
        List<Integer> maxKeys = new ArrayList<>();

        // 遍历排序后的List对象，并将前三个键存储到新的List对象中
        int count = 0;
        for (Map.Entry<Integer, Integer> entry : list) {
            if (count < 3) {
                maxKeys.add(entry.getKey());
                count++;
            } else {
                break;
            }
        }

//        // 输出结果
//        System.out.println("HashMap: " + recommendationDict);
//        System.out.println("Value最大的三个键: " + maxKeys);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
